const app = getApp();
var thatAll;
const BT = JSON.stringify(Str2Bytes("aa55a55a")); //通用包头
const BW = JSON.stringify(Str2Bytes("cc66c66c")); //通用包尾
const  writeServicesId="0000FFE5-0000-1000-8000-00805F9B34FB"
const  writeCharacteristicsId= "0000FFE9-0000-1000-8000-00805F9B34FB" //写UUID， 根据蓝牙模块获得
const notifyServicesId="0000FFE0-0000-1000-8000-00805F9B34FB"//响应
const notifyCharacteristicsId= "0000FFE4-0000-1000-8000-00805F9B34FB" //响应UUID，根据蓝牙模块获得
const notifyServicesId_second ="0000FFE0-0000-1000-8000-00805F9B34FB";//响应
const notifyCharacteristicsId_second = "0000FFE2-0000-1000-8000-00805F9B34FB"; //响应UUID，根据蓝牙模块获得
const writeServicesId_second ="0000FFE0-0000-1000-8000-00805F9B34FB";
const writeCharacteristicsId_second =  "0000FFE1-0000-1000-8000-00805F9B34FB"; //写UUID， 根据蓝牙模块获得
var notifyServicesId_now ="";//响应
var notifyCharacteristicsId_now = ""; //响应UUID，根据蓝牙模块获得
var writeServicesId_now ="";
var writeCharacteristicsId_now =  ""; //写UUID， 根据蓝牙模块获得
var connectedDeviceId ="" //连接上的设备的ID
Page({
  data: {
    state:1,
    nowIdentity:"",
    configYear:"23",
    configMonth:"12",
    configP:"01",
    configFirst:"00",
    configLast:"00",
    eqFirst:"40",
    dianliang:"0",
    zhuangtai:"00",
    time:2,
    pl:2,
    workTime:10,
    bluetoothModel:"01",
    gear1:"02",
    gear2:"05",
    gear3:"10",
    gear4:"15",
    imgurl:"../../images/fanzhuan1.png",
    deviceId:"",
  },
   onShow :function () {
     //体验版：体验版删除数据，发布时屏蔽掉
     if(app.nowEquipmentId){
      this.setData({
        nowIdentity : app.nowEquipmentId,
        configYear:app.nowEquipmentId.substr(4,2),
        configP:app.nowEquipmentId.substr(6,2),
        configFirst:app.nowEquipmentId.substr(8,2),
        configLast:app.nowEquipmentId.substr(10,2)
      })
     }
   },
   toggleDropdown() {
    this.setData({
      isDropdownVisible:!this.data.isDropdownVisible
    });
  },
  //高度
  onLoad: function () {
    var that = this;
    thatAll = that;
   //体验版：体验版删除数据，发布时屏蔽掉
   if(app.nowEquipmentId){
    this.setData({
      nowIdentity : app.nowEquipmentId,
      configYear:app.nowEquipmentId.substr(4,2),
      configP:app.nowEquipmentId.substr(6,2),
      configFirst:app.nowEquipmentId.substr(8,2),
      configLast:app.nowEquipmentId.substr(10,2)
    })
   }
  },
  fanzhuan:function () {
    BLEDataSend("aa55a55a210100cc66c66c");
   },
   fanzhuanS:function () {
    BLEDataSend("aa55a55a210101cc66c66c");
   },
   fanzhuanX:function () {
    BLEDataSend("aa55a55a210102cc66c66c");
   },
   danci:function () {
    var that = this;
    that.setData({
       zhuangtai:"00"
     })
    BLEDataSend("aa55a55a2000cc66c66c");
   },
   wushi:function () {
    var that = this;
    that.setData({
       zhuangtai:"01"
     })
    BLEDataSend("aa55a55a2001cc66c66c");
   },
   zidong:function () {
    var that = this;
    that.setData({
       zhuangtai:"02"
     })
    BLEDataSend("aa55a55a2002cc66c66c");
   },
  /**设备号设置：加减 */
  configAddReduce(e){
    var that = this;
    var prop = e.target.dataset.prop;
    var type = e.target.dataset.type;
    if(prop == "configYear"){
      var configYear = that.data.configYear;
      if(type == 'add'){
        configYear = parseInt(configYear) + 1;
      }else if(type == 'reduce'){
        if(configYear > 1){
          configYear = parseInt(configYear) - 1;
        }
      }
      that.setData({
        configYear : formatNumber(configYear)
      })
    }else if(prop == "configMonth"){
      var configMonth = that.data.configMonth;
      if(type == 'add'){
        if(configMonth <12){
          configMonth = parseInt(configMonth)+1;
        }else{
          configMonth = 1;
        }
      }else if(type == 'reduce'){
        if(configMonth >1){
          configMonth = parseInt(configMonth) - 1;
        }else{
          configMonth = 12;
        }
      }
      that.setData({
        configMonth: formatNumber(configMonth)
      })
    }else if(prop == "configP"){
      var configP = that.data.configP;
      if(type == 'add'){
        if(configP < 9){
          configP = parseInt(configP)+1;
        }else{
          configP = 1;
        }
      }else if(type == 'reduce'){
        if(configP > 1){
          configP = parseInt(configP) - 1;
        }else{
          configP = 9;
        }
      }
      that.setData({
        configP: formatNumber(configP)
      })
    }else if(prop == "configFirst"){
      var configFirst = that.data.configFirst;
      if(type == 'add'){
        if(configFirst < 99){
          configFirst =  parseInt(configFirst)+1;
        }else{
          configFirst = 0;
        }
      }else if(type == 'reduce'){
        if(configFirst > 0){
          configFirst =  parseInt(configFirst) - 1;
        }else{
          configFirst = 99;
        }
      }
      that.setData({
        configFirst: formatNumber(configFirst)
      })
    }else if(prop == "configLast"){
      var configLast = that.data.configLast;
      if(type == 'add'){
        if(configLast < 99){
          configLast =  parseInt(configLast)+1;
        }else{
          configLast = 0;
        }
      }else if(type == 'reduce'){
        if(configLast > 0){
          configLast =  parseInt(configLast) - 1;
        }else{
          configLast = 99;
        }
      }
      that.setData({
        configLast: formatNumber(configLast)
      })
    }
  },
  /**频率加减 */
  pinlv(e) {
    var that = this;
    var type = e.target.dataset.type;
    var pl = that.data.pl;
    if(type == 'add'){
      if(pl < 30){
        pl = parseInt(pl) + 1;
      }else{
        pl = 2;
      }
    }else if(type == 'reduce'){
      if(pl > 2){
        pl = parseInt(pl) - 1;
      }else{
        pl = 30;
      }
    }
    that.setData({
      pl:pl
    })
  },
  /**工作时长加减 */
  workTimeConfig(e){
    var that = this;
    var type = e.target.dataset.type;
    var workTime = that.data.workTime;
    if(type == 'add'){
      if(workTime < 30){
        workTime = parseInt(workTime) + 1;
      }else{
        workTime = 5;
      }
    }else if(type == 'reduce'){
      if(workTime > 5){
        workTime = parseInt(workTime) - 1;
      }else{
        workTime = 30;
      }
    }
    that.setData({
      workTime:workTime
    })
  },
  /**档位设置：加减 */
  pearAddReduce(e){
    var that = this;
    var prop = e.target.dataset.prop;
    var type = e.target.dataset.type;
    if(prop == "gear1"){
      var gear1 = that.data.gear1;
      if(type == 'add'){
        if(gear1 < 30){
          gear1 = parseInt(gear1) + 1;
        }else{
          gear1 = 2;
        }
      }else if(type == 'reduce'){
        if(gear1 > 2){
          gear1 = parseInt(gear1) - 1;
        }else{
          gear1 = 30;
        }
      }
      that.setData({
        gear1 : formatNumber(gear1)
      })
    }else if(prop == "gear2"){
      var gear2 = that.data.gear2;
      if(type == 'add'){
        if(gear2 < 30){
          gear2 = parseInt(gear2)+1;
        }else{
          gear2 = 2;
        }
      }else if(type == 'reduce'){
        if(gear2 >2){
          gear2 = parseInt(gear2) - 1;
        }else{
          gear2 = 30;
        }
      }
      that.setData({
        gear2: formatNumber(gear2)
      })
    }else if(prop == "gear3"){
      var gear3 = that.data.gear3;
      if(type == 'add'){
        if(gear3 < 30){
          gear3 = parseInt(gear3)+1;
        }else{
          gear3 = 2;
        }
      }else if(type == 'reduce'){
        if(gear3 > 2){
          gear3 = parseInt(gear3) - 1;
        }else{
          gear3 = 30;
        }
      }
      that.setData({
        gear3: formatNumber(gear3)
      })
    }else if(prop == "gear4"){
      var gear4 = that.data.gear4;
      if(type == 'add'){
        if(gear4 < 30){
          gear4 =  parseInt(gear4)+1;
        }else{
          gear4 = 2;
        }
      }else if(type == 'reduce'){
        if(gear4 > 2){
          gear4 =  parseInt(gear4) - 1;
        }else{
          gear4 = 30;
        }
      }
      that.setData({
        gear4: formatNumber(gear4)
      })
    }
  },
  /**发送频率设置 */
  pinlvConfig(){
    var that = this;
    var pl = that.data.pl;
    if(!range(pl,30,2)){//不在范围内
      wx.showToast({
        title: "频率范围为2~30",
        icon: "none",
        mask: false, 
        duration:1000 
      });
      return;
    }
    var message = "aa55a55a22"+formatNumber(parseInt(pl).toString(16))+"cc66c66c";
    BLEDataSend(message);
  },
  /**时间加减 */
  timeConfig(e) {
    var that = this;
    var type = e.target.dataset.type;
    var time = that.data.time;
    if(type == 'add'){
      if(time < 30){
        time = parseInt(time) + 1;
      }else{
        time = 2;
      }
    }else if(type == 'reduce'){
      if(time > 2){
        time = parseInt(time) - 1;
      }else{
        time = 30;
      }
    }
    that.setData({
      time:time
    })
  },
  /**发送时间设置 */
  sendTime(){
    var that = this;
    var time = that.data.time;
    if(!range(time,30,2)){//不在范围内
      wx.showToast({
        title: "翻转间隔为2~30s",
        icon: "none",
        mask: false, 
        duration:1000 
      });
      return;
    }
    var message = "aa55a55a23"+formatNumber(parseInt(time).toString(16))+"cc66c66c";
    BLEDataSend(message);
  },
  /**发送工作时长 */
  workTime:function () {
    var that = this;
    var workTime = that.data.workTime;
    if(!range(workTime,30,5)){//不在范围内
      wx.showToast({
        title: "工作时长为5~30分钟",
        icon: "none",
        mask: false, 
        duration:1000 
      });
      return;
    }
    var message = "aa55a55a2b"+formatNumber(parseInt(workTime).toString(16))+"cc66c66c";
    BLEDataSend(message);
   },
  /**体验版设置： 单选框*/
  handleChange(e){
     var that = this;
     that.setData({
       eqFirst:e.detail.value
     })
  },
  /**体验版设置：修改设备号 */
  changeEqName(){
    var that = this;
    var year = that.data.configYear;
    var configMonth = that.data.configMonth;
    var configFirst = that.data.configFirst;
    var configLast = that.data.configLast;
    var message = "aa55a55a260400"+
    formatNumber(parseInt(year[0]).toString(16))+
    formatNumber(parseInt(year[1]).toString(16))+
    formatNumber(parseInt(configMonth[0]).toString(16))+
    formatNumber(parseInt(configMonth[1]).toString(16))+
    formatNumber(parseInt(configFirst[0]).toString(16))+
    formatNumber(parseInt(configFirst[1]).toString(16))+
    formatNumber(parseInt(configLast[0]).toString(16))+
    formatNumber(parseInt(configLast[1]).toString(16))+
    "cc66c66c";

    //console.log("message："+message);
    BLEDataSend(message);
   //sendTy("444D313032333035313033303130");
   //sendTy(newName);

  },
  /**发送档位设置 */
  sendGear(){
    var that = this;
    var gear1 = that.data.gear1;
    var gear2 = that.data.gear2;
    var gear3 = that.data.gear3;
    var gear4 = that.data.gear4;
    if(!range(gear1,30,2) || !range(gear2,30,2) || !range(gear3,30,2) || !range(gear4,30,2)){//不在范围内
      wx.showToast({
        title: "翻转间隔为2~30s",
        icon: "none",
        mask: false, 
        duration:1000 
      });
      return;
    }
    var message = "aa55a55a2c"+
    formatNumber(parseInt(gear1).toString(16))+
    formatNumber(parseInt(gear2).toString(16))+
    formatNumber(parseInt(gear3).toString(16))+
    formatNumber(parseInt(gear4).toString(16))+
    "cc66c66c";
    BLEDataSend(message);
  },
  /**体验版设置：输入框值改变 */
  inputOnChange(e) {
    this.setData({
      [e.currentTarget.dataset.prop]:e.detail.value
    });
  },
  /**切换设备，模式 */
  bluetoothModel(){
    var that = this;
    wx.showActionSheet({
      itemList: ['非蓝牙模式', '蓝牙模式'],
      success (res) {
        var model = res.tapIndex;
        var bluetoothModel = that.data.bluetoothModel;
        if(model == 0){
          bluetoothModel = "01";
          BLEDataSend("aa55a55a2a01cc66c66c")
        }else if(model == 1){
          bluetoothModel = "02"
          BLEDataSend("aa55a55a2a02cc66c66c")
        }
        that.setData({
          bluetoothModel:bluetoothModel
         })
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })
  },
  /** 点击事件 */
  index:function(e){
  var that = this;
  var state = e.currentTarget.dataset.state;
  if(state == 1){
    wx.navigateTo({
      url: '/pages/index/index',
    });
  }else{
    closeBLEConnection();
  }
  },
  start() {
    var that = this;
    that.setData({
      imgurl:"../../images/fanzhuan2.png",
    })
  },
  end() {
  var that = this;
  that.setData({
    imgurl:"../../images/fanzhuan1.png",
  })
}
});

/**    蓝牙        */








  /****************5.连接蓝牙设备***************/
  function BLEConnect(event)
  {
    wx.createBLEConnection
    ({
      deviceId: event.target.id,
      timeout:20000,
      success: function (res) 
      {
        //console.log("red："+JSON.stringify(res))
          wx.getBLEDeviceServices({
            deviceId:event.target.id,
            success:function(res){
              for(var i=0;i<res.services.length;i++){
                var serviceId =  res.services[i].uuid;
                //console.log("serviceId："+serviceId);
                wx.getBLEDeviceCharacteristics({
                  deviceId: event.target.id,
                  serviceId:serviceId,
                  success:function(res){
                    for (let i = 0; i < res.characteristics.length; i++) {
                      //console.log("serviceId："+serviceId+"   characteristicsId:"+res.characteristics[i].uuid);
                      var flag = false;
                      if(res.characteristics[i].uuid == notifyCharacteristicsId){
                        console.log("旧版："+notifyCharacteristicsId);
                         notifyServicesId_now = notifyServicesId;
                         notifyCharacteristicsId_now = notifyCharacteristicsId;
                         writeServicesId_now = writeServicesId;
                         writeCharacteristicsId_now =  writeCharacteristicsId;
                         flag = true;
                      }else if(res.characteristics[i].uuid == notifyCharacteristicsId_second){
                        //console.log("新版："+notifyCharacteristicsId);
                        notifyServicesId_now = notifyServicesId_second;
                        notifyCharacteristicsId_now = notifyCharacteristicsId_second;
                        writeServicesId_now = writeServicesId_second;
                        writeCharacteristicsId_now =  writeCharacteristicsId_second;
                        flag = true;
                      }
                      //console.log("flag："+flag)
                      if(flag){
                        var identity = event.currentTarget.dataset.identity;//连接的设备名字
                        app.identity = identity.replace(/[\r\n ]/g,"");//全局变量
                        thatAll.setData({
                          state : 2,
                          nowIdentity:app.identity
                        });
                        app.nowEquipmentId = app.identity;
                        connectedDeviceId= event.currentTarget.id;//连接设备id
                     //连接设备id
                        BLECharacteristicValueChange();//启用特征值变化
                        BLEDataRecieve();//接收信息
                        jiance()//监测状态 
                        wx.hideLoading();
                      }
                    }
                  }
          
                })
            }
          }
          })
        //getBLEDeviceServices(event.target.id);
      },
      fail: function (res) 
      {
        console.log("fail："+JSON.stringify(res))
        wx.showModal({
          title: '提示',
          content:  res.errMsg,
          success (res) {
       
          }
        })
      },
      complete:function(){
        BLESearchStop();
      }
    })
  }
/***
 * 判断两个蓝牙模块
 */
function connectLy(deviceId,){

}
 function getBLEDeviceServices(deviceId) {
  return promisify(wx.getBLEDeviceServices, {
    deviceId: deviceId
  }).then(res => {
    for(var i=0;i<res.services.length;i++){
      //       console.log(res.services[i].uuid);
    }
      return res
  }, err => {
   // console.log("失败："+res)
      return err
  })

  }
  function promisify(fn, args) {
    return new Promise((resolve, reject) => {
        fn({
            ...(args || {}),
            success: (res) => resolve(res),
            fail: (err) => reject(err),
        });
    });
}
  /****************6.停止搜索蓝牙设备***************/
  function BLESearchStop(event)
  {
    wx.stopBluetoothDevicesDiscovery
    ({
      success: function (res) 
      {
       // console.log("停止搜索" + JSON.stringify(res.errMsg));
      }
    })
  }
  /****************9.启用特征值变化***************/
  function BLECharacteristicValueChange(event)
  {
   // console.log("启用的notifyCharacteristicsId", notifyCharacteristicsId);
    wx.notifyBLECharacteristicValueChange
    ({
      state: true,
      deviceId: connectedDeviceId,
      serviceId: notifyServicesId_now,//响应
      characteristicId: notifyCharacteristicsId_now,
      success: function (res) 
      {
        // console.log('notifyBLECharacteristicValueChange success', res.errMsg)
      },
      fail: function (res) 
      {
        //.log('启动notify:' + res.errMsg);
      },
      
    })
  }
  /****************10.接收蓝牙的返回数据***************/
  function BLEDataRecieve(event)
  {
   // console.log("开始接收数据");
    wx.onBLECharacteristicValueChange
    (
      function (res) 
      {
        //可以直接setdata设置显示数据
       // console.log("characteristicId：" + res.characteristicId)
       // console.log("serviceId:" + res.serviceId)
        //console.log("deviceId" + res.deviceId)
        //console.log("Length:" + res.value.byteLength)
        var data = ab2hex(res.value);
        console.log("返回数据:" + data)
        var bytes = Str2Bytes(data);
        analysis(bytes);//数据解析 
      
      }
    )
  }
  //监测
  function jiance() {
    wx.onBLEConnectionStateChange(function(res) {
   // 该方法回调中可以用于处理连接意外断开等异常情况
    if(res.connected){
      thatAll.setData({
        state : 2
      })
    }else{
      thatAll.setData({
        state : 1,
        nowIdentity:"",
        dianliang:"0"
      });
      closeBLEConnection();
    }
    // console.log(thatAll.data.state)
    // console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
})
  }
 //数据解析
  function analysis(bytes){
      for(var i=0;i<bytes.length;i++){ 
          //剩余长度大于2
          if(i < bytes.length - 2){
              //验证包头
            if(BT == JSON.stringify(bytes.slice(i,i+4))){
              if(BW == JSON.stringify(bytes.slice(i+6,i+10))){//包左不包右，2个包体
                //判断指令包
                var type = bytes[i+4];
                var body2 = bytes[i+5];
                //console.log("2包体，类型："+type)
                if(type == "10"){//状态：自动、雾视、单次
                  var zt = "";
                  if(body2 =="00"){
                    zt = "00"
                  }else if(body2 =="01"){
                    zt = "01"
                  }else if(body2 =="02"){
                    zt = "02"
                  }
                  thatAll.setData({
                    zhuangtai : zt
                  })
                }else if(type == "12"){//频率
                  thatAll.setData({
                    pl : parseInt(body2,16)
                  })
                }else if(type == "13"){//时间间隔
                  thatAll.setData({
                    time : parseInt(body2,16)
                  })
                }else if(type == "15"){//电量
                  thatAll.setData({
                    dianliang : parseInt(body2,16)
                  })
                }else if(type == "1a"){//设备模式
                  thatAll.setData({
                    bluetoothModel : body2
                  })
                }else if(type == "1b"){//工作时长
                  thatAll.setData({
                    workTime : parseInt(body2,16)
                  })
                }
              }
                //验证包尾
              if(BW == JSON.stringify(bytes.slice(i+7,i+11))){//包左不包右,3个包体
                  //判断指令包
                  var type = bytes[i+4];
                  var body2 = bytes[i+5];
                  //var value = parseInt(bytes[i+6],16);//设置的值，暂时不用
                  //console.log("3包体，类型："+type)
                  if(type == "1f"){//握手回复
                    //握手回复
                    BLEDataSend("aa55a55a2f5152cc66c66c");
                  }else if(type == "1e"){//设置返回提示
                    var msg = returnMessage(body2);
                    if(body2 != "21"){
                      if(msg){
                        wx.showToast({
                          title: msg,
                          icon: "none",
                          mask: false, 
                          duration:1000 
                        })
                      }
                    }
                  }
              }
              if(BW == JSON.stringify(bytes.slice(i+9,i+13))){//包左不包，5个包体
                var type = bytes[i+4];
                var body2 = bytes[i+5];
                var body3 = bytes[i+6];
                var body4 = bytes[i+7];
                var body5 = bytes[i+8];
                if(type == "1c"){
                  thatAll.setData({
                    gear1 : formatNumber(parseInt(body2,16)),
                    gear2 : formatNumber(parseInt(body3,16)),
                    gear3 : formatNumber(parseInt(body4,16)),
                    gear4 : formatNumber(parseInt(body5,16)),
                  })
                }
              }
            }
          }
      }
  }

/****************11.蓝牙发送数据***************/
 function BLEDataSend(message){
  console.log('要发送的信息是：'+message)
  var buffer1 = string2ArrayBuffer(message);
  wx.writeBLECharacteristicValue
  ({
    deviceId: connectedDeviceId,
    serviceId: writeServicesId_now,
    characteristicId: writeCharacteristicsId_now,
    // 这里的value是ArrayBuffer类型
    value: buffer1,
    success: function (res) 
    {
     // console.log('写入成功', res.errMsg)
    },
    fail(res)
    {
    //  console.log('写入失败', res.errMsg)
    }
  })
}
  //断开蓝牙
  function closeBLEConnection(){
    wx.closeBLEConnection({
      deviceId: connectedDeviceId,
      success: function (res) {
        connectedDeviceId= "",
        wx.showToast({
          title: '蓝牙已断开',
          icon: "none",
          mask: false, 
          duration:1000 
        })
        thatAll.setData({
          state :1,
          dianliang:"0",
          nowIdentity:""
        });
      },
      fail:function(res){
       // console.log('断开蓝牙设备失败：' + res.errMsg)
      }
    })

  }
/**判断返回类型 */
function returnMessage(model) {
  var msg = "";
  switch(model){
     case "20": msg = "翻转模式设置成功";break;
     case "21": break;
     case "22": msg = "频率设置成功";break;
     case "23": msg = "间隔设置成功";break;
     case "25": msg = "档位设置成功";break;
     case "26": msg = "设备重命名成功";break;
     case "2a": msg = "模式设置成功";break;
     case "2b": msg = "工作时长设置成功";break;
     case "2c": msg = "档位时长设置成功";break;
  }
  return msg;
}
/**字符串转16进制 */
function stringToHex(str){
  var val = "";
  for (var i = 0; i < str.length; i++) {
      if (val == "") {
          val = str.charCodeAt(i).toString(16);        //获取字符的Unicode码然后转16进制
      } else {
          val += str.charCodeAt(i).toString(16);//获取字符的Unicode码然后转16进制再拼接,中间用逗号隔开
      }
  }
  return val;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
 // console.log("类型："+Object.prototype.toString(hexArr))
  return hexArr.join('');
}
function string2ArrayBuffer(val) { //传过来是字符串类型指令  包头+包体+包尾
  // 首先将字符串转为16进制
  //let val = ""
  // for (let i = 0; i < str.length; i++) {
  //   if (val === '') {
  //     val = str.charCodeAt(i).toString(16) 
  //   } else {
  //     val += ',' + str.charCodeAt(i).toString(16)
  //   }
  // }
  // 将16进制转化为ArrayBuffer
  return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  })).buffer
}
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
function Str2Bytes(str)
{
    var pos = 0;
    var len = str.length;
    if(len %2 != 0)
    {
       return null;
    }
    len /= 2;
    var hexA = new Array();
    for(var i=0; i<len; i++)
    {
        var s = str.substr(pos, 2);
       // var v = parseInt(s, 16);
        hexA.push(s);
        pos += 2;
    }
    return hexA;
}

//补0
const formatNumber = (num) => {
	num = num.toString()
	return num[1] ? num : '0' + num
}
//截取字符串
function substrBytes(bytes,begin,end){
  return  bytes.slice(begin,end);
}
/**判断范围 */
function range(value,max,min) {
  if(value !=''&& value >= min && value <= max){
    return true;
  }
  return false;
}


module.exports = {
  BLEConnect:BLEConnect,
  BLEDataSend:BLEDataSend,
  closeBLEConnection:closeBLEConnection,
}